﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Automation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
using AudioBooks.Data;
using AudioBooks.SQLite;
using AudioBooks.ViewModel;

namespace AudioBooks.Controls
{
    public sealed partial class Player : UserControl
    {
        public bool _sliderpressed { get; set; }

        public Player()
        {
            this.InitializeComponent();
          

        
            if (App.Player != null)
            {

                //timelineSlider.ValueChanged += timelineSlider_ValueChanged;
                //PointerEventHandler pointerpressedhandler = new PointerEventHandler(slider_PointerEntered);
                //timelineSlider.AddHandler(Control.PointerPressedEvent, pointerpressedhandler, true);

                //PointerEventHandler pointerreleasedhandler = new PointerEventHandler(slider_PointerCaptureLost);
                //timelineSlider.AddHandler(Control.PointerCaptureLostEvent, pointerreleasedhandler, true);
                App.Player.CurrentStateChanged += mainPlayer_CurrentStateChanged;
                App.Player.MediaOpened += mainPlayer_MediaOpened;
                App.Player.MediaEnded += mainPlayer_MediaEnded;
               
            }

            timelineSlider.ValueChanged += timelineSlider_ValueChanged;
        }

       

        private void timelineSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
        {

            Runtime.Text = FormatTimeSpan(App.Player.Position);
            //System.Diagnostics.Debug.WriteLine("Slider old value = {0} new value = {1}.", e.OldValue, e.NewValue);
            if (!_sliderpressed)
            {
                App.Player.Position = TimeSpan.FromSeconds(e.NewValue);
            }
          
        }

        private void mainPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            StopTimer();
            timelineSlider.Value = 0.0;
            //await NextChapter();
        }

        private double SliderFrequency(TimeSpan timevalue)
        {
            double stepfrequency = -1;

            double absvalue = (int)Math.Round(timevalue.TotalSeconds, MidpointRounding.AwayFromZero);
            stepfrequency = (int)(Math.Round(absvalue / 100));

            if (timevalue.TotalMinutes >= 10 && timevalue.TotalMinutes < 30)
            {
                stepfrequency = 10;
            }
            else if (timevalue.TotalMinutes >= 30 && timevalue.TotalMinutes < 60)
            {
                stepfrequency = 30;
            }
            else if (timevalue.TotalHours >= 1)
            {
                stepfrequency = 60;
            }

            if (stepfrequency == 0) stepfrequency += 1;

            if (stepfrequency == 1)
            {
                stepfrequency = absvalue / 100;
            }

            return stepfrequency;
        }

        private void mainPlayer_MediaOpened(object sender, RoutedEventArgs e)
        {
            double absvalue = (int)Math.Round(App.Player.NaturalDuration.TimeSpan.TotalSeconds, MidpointRounding.AwayFromZero);
            timelineSlider.Maximum = absvalue;
            timelineSlider.StepFrequency = SliderFrequency(App.Player.NaturalDuration.TimeSpan);
            txtTotalTime.Text = FormatTimeSpan(App.Player.NaturalDuration.TimeSpan);
            SetupTimer();

            if (App.PlayIndex == 0)
            {
                BackButton.IsEnabled = false;
            }
            else
            {
                if (App.PlayIndex == App.GlobalPlaylist.Count - 1)
                    NextButton.IsEnabled = false;
                else
                {
                    NextButton.IsEnabled = true;
                    BackButton.IsEnabled = true;
                }
            }
        }

        private void mainPlayer_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            if (App.Player.CurrentState == Windows.UI.Xaml.Media.MediaElementState.Paused)
            {
                PauseButton.Content = "";
                AutomationProperties.SetName(PauseButton, "Resume");
               
                BackButton.IsEnabled = true;
                PauseButton.IsEnabled = true;
                NextButton.IsEnabled = true;
                StopButton.IsEnabled = true;
                timelineSlider.IsEnabled = true;
            }
            else
            {
                if (App.Player.CurrentState == Windows.UI.Xaml.Media.MediaElementState.Playing)
                {
                    PauseButton.Content = "";
                    AutomationProperties.SetName(PauseButton, "Pause");
                    BackButton.IsEnabled = true;
                    NextButton.IsEnabled = true;
                    StopButton.IsEnabled = true;
                    PauseButton.IsEnabled = true;
                    timelineSlider.IsEnabled = true;
                    txtTotalTime.Text = FormatTimeSpan(App.Player.NaturalDuration.TimeSpan);
                }
                else
                {
                    if (App.Player.CurrentState == Windows.UI.Xaml.Media.MediaElementState.Stopped)
                    {
                        PauseButton.Content = "";
                        AutomationProperties.SetName(PauseButton, "Replay");
                        BackButton.IsEnabled = false;
                        NextButton.IsEnabled = false;
                        PauseButton.IsEnabled = true;
                        StopButton.IsEnabled = false;
                        timelineSlider.IsEnabled = false;
                    }
                    else
                    {
                        PauseButton.Content = "";
                        AutomationProperties.SetName(PauseButton, "Resume");
                        BackButton.IsEnabled = false;
                        NextButton.IsEnabled = false;
                        PauseButton.IsEnabled = false;
                        StopButton.IsEnabled = false;
                        timelineSlider.IsEnabled = false;
                    }
                   
                }


            }


        }
        string FormatTimeSpan(TimeSpan timeSpan)
        {
            var sb = new StringBuilder();

            if (timeSpan < TimeSpan.Zero)
            {
                sb.Append('-');

                timeSpan = -timeSpan;
            }

            if (timeSpan.Days > 1)
                sb.AppendFormat(timeSpan.ToString(@"%d\."));

            sb.Append(timeSpan.ToString(@"hh\:mm\:ss"));

            return sb.ToString();
        }

        private void PauseButton_Click(object sender, RoutedEventArgs e)
        {
            if (App.Player.CurrentState == Windows.UI.Xaml.Media.MediaElementState.Playing)
            {
                App.Player.Pause();
                MediaControl.IsPlaying = false;
                PauseButton.Content = "";
                AutomationProperties.SetName(PauseButton, "Resume");
            }
            else
            {
                if (App.Player.CurrentState == Windows.UI.Xaml.Media.MediaElementState.Stopped)
                {
                    double absvalue = (int)Math.Round(App.Player.NaturalDuration.TimeSpan.TotalSeconds, MidpointRounding.AwayFromZero);
                    timelineSlider.Maximum = absvalue;
                    timelineSlider.StepFrequency = SliderFrequency(App.Player.NaturalDuration.TimeSpan);
                    txtTotalTime.Text = FormatTimeSpan(App.Player.NaturalDuration.TimeSpan);
                    SetupTimer();
                    App.Player.Play();
                    if (App.PlayIndex == 0)
                    {
                        BackButton.IsEnabled = false;
                    }
                    else
                    {
                        if (App.PlayIndex == App.GlobalPlaylist.Count - 1)
                            NextButton.IsEnabled = false;
                        else
                        {
                            NextButton.IsEnabled = true;
                            BackButton.IsEnabled = true;
                        }
                    }

                }
                else
                {
                    App.Player.Play();
                    MediaControl.IsPlaying = true;
                    PauseButton.Content = "";
                    AutomationProperties.SetName(PauseButton, "Pause");
                }
               
            }
        }


        public delegate void AddControlEvent(StorageFile eFile);

        public event AddControlEvent AddControl;

        public event EventHandler AddBookMark;

        private DispatcherTimer timer;
        private void SetupTimer()
        {
            if (timer != null)
                timer = null;
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1.0);
            timer.Tick += _timer_Tick;
            timer.Start();
        }

        private void _timer_Tick(object sender, object e)
        {
            if (!_sliderpressed)
            {
                timelineSlider.Value = App.Player.Position.TotalSeconds;
            }
        }
        private void StopTimer()
        {
            timer.Stop();
            timer.Tick -= _timer_Tick;
        }

    
        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            timelineSlider.Value = 0;
            App.Player.Stop();
            StopTimer();
        }

     

        private void BackButton_Click(object sender, RoutedEventArgs e)
        {

            var getListFile = App.GlobalPlaylist.ToList();
            if (getListFile.Count > 0)
            {
                
                if (App.PlayIndex > 0)
                {
                    App.PlayIndex--;
                    if (AddControl != null)
                        AddControl(getListFile[App.PlayIndex]);
                }

                else
                {
                    MessageDialog message = new MessageDialog("End list chapter");
                    message.ShowAsync();
                }

            }
        }

        private void NextButton_Click(object sender, RoutedEventArgs e)
        {
            var getListFile = App.GlobalPlaylist.ToList();
            if (getListFile.Count > 0)
            {
                if (App.PlayIndex < getListFile.Count)
                {
                    App.PlayIndex++;
                    if (AddControl != null)
                        AddControl(getListFile[App.PlayIndex]);
                }
                else
                {
                    MessageDialog message = new MessageDialog("End list chapter");
                    message.ShowAsync();
                }
            }
        }
       

        private async void Button_Tapped(object sender, TappedRoutedEventArgs e)
        {
            var BookMark = new PlayChapterInfo()
            {
                BookId = App.NowPlayBookId,
                Position = App.Player.Position,
                ChapterName = App.NowPlayChapterId,
                ImagePath = ((PlayerViewModel)DataContext).ImageLink,
                BookName = App.NowPlayTitle
            };
            if (string.IsNullOrEmpty(BookMark.BookId) || string.IsNullOrEmpty(BookMark.ChapterName))
            {
                MessageDialog message = new MessageDialog("Please choose chapter before.");
                await message.ShowAsync();
                return;
            }
            HandlePlayChapter.SaveDataPlayChapterInfo(BookMark);
            if(AddBookMark != null)
            {
                AddBookMark(sender, new EventArgs());
            }
        }
      
    }
}
